﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;
public partial class Manage_basisset_user : AdminPageBase
{
    private string SearchWord;
    private string returnURL;
    private int SearchFlag;
    
    protected void Page_Load(object sender, EventArgs e)
    {
        CheckAdmin();
        GetUserPermisions();
        if (!IsPostBack)
        {
            // 正确的属性设置方法
            this.grdvUser.Attributes.Add("SortExpression", "UserId");
            this.grdvUser.Attributes.Add("SortDirection", "ASC");
            getParam();
            if (SearchFlag == 1)
            {
                BindUser();
            }
            else
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("UserId");
                dt.Columns.Add("GroupId");
                dt.Columns.Add("GroupName");
                dt.Columns.Add("PWD");
                dt.Columns.Add("Code");
                dt.Columns.Add("Name");
                dt.Columns.Add("IsValid");
                dt.Columns.Add("IsValidDesc");
                dt.Columns.Add("");

                GridviewControl.GridViewDataBind(this.grdvUser, dt);
                GridviewControl.ResetGridView(this.grdvUser);
            }
           // BindUser();
          
            if (add == 1)
            {
               
                adduser.Enabled = true;
            }
            else
            {
               
                adduser.Enabled = false;
            }

        }
    }
    private void getParam()
    {
        if (!string.IsNullOrEmpty(Request.QueryString["SearchWord"]))
        {
            SearchWord = Request.QueryString["SearchWord"];
            txtkeyword.Text = SearchWord;
        }
        if (!string.IsNullOrEmpty(Request.QueryString["SearchFlag"]))
            SearchFlag = Convert.ToInt32(Request.QueryString["SearchFlag"]);

    }
    protected void CheckAdmin()
    {
        if (AdminSessionHelper.UserDetails == null)
        {
            JsHelper.TopAlertRedirect("请先登录", "../login.aspx", this.Page);
        }
    }
    protected void BindUser()
    {     

         // 获取GridView排序数据列及排序方向
         string sortExpression = this.grdvUser.Attributes["SortExpression"];
         string sortDirection = this.grdvUser.Attributes["SortDirection"];

         string keyword = txtkeyword.Text.Trim();
         if (CoreTools.ProcessSqlStr(keyword, 0))
         {
             DataSet ds = jtDataAccess.SearchUser(keyword, pager1.PageSize, pager1.CurrentPageIndex, sortExpression, sortDirection);
             if (CoreTools.CheckDataSet(ds))
             {
                 // 根据GridView排序数据列及排序方向设置显示的默认数据视图
                 if ((!string.IsNullOrEmpty(sortExpression)) && (!string.IsNullOrEmpty(sortDirection)))
                 {
                     ds.Tables[0].DefaultView.Sort = string.Format("{0} {1}", sortExpression, sortDirection);
                 }

                 // GridView绑定并显示数据
                 GridviewControl.GridViewDataBind(this.grdvUser, ds.Tables[0]);
                 pager1.RecordCount = Convert.ToInt32(ds.Tables[0].Rows[0]["qty"]);
             }
             else
             {
                 DataTable dt = new DataTable();
                 dt.Columns.Add("UserId");
                 dt.Columns.Add("GroupId");
                 dt.Columns.Add("GroupName");
                 dt.Columns.Add("PWD");
                 dt.Columns.Add("Code");
                 dt.Columns.Add("Name");
                 dt.Columns.Add("IsValid");
                 dt.Columns.Add("IsValidDesc");
                 dt.Columns.Add("");
                 GridviewControl.GridViewDataBind(this.grdvUser, dt);
                 pager1.RecordCount = 0;
             }
         }
         else
         {
             ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert(ConfigHelper.ProcessSqlStrErroMsg), false);
             txtkeyword.Focus();
         }
    }


    protected void pager1_PageChanged(object sender, EventArgs e)
    {
        BindUser();
    }
  
    //protected string GetGroupName(int userid)
    //{
    //    string groupname = "";
    //    DataSet ds = jtDataAccess.GetUserInfo(userid);
    //    if (CoreTools.CheckDataSet(ds))
    //        groupname = ds.Tables[0].Rows[0]["GroupName"].ToString();
    //    return groupname;
    //}
    //protected int GetGroupId(int userid)
    //{
    //    int groupid = 0;
    //    DataSet ds = jtDataAccess.GetUserInfo(userid);
    //    if (CoreTools.CheckDataSet(ds))
    //        groupid = int.Parse(ds.Tables[0].Rows[0]["GroupId"].ToString());
    //    return groupid;
    //}
    protected void grdvUser_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        string name, code, pwd, isvalid, groupid, groupName;
        int userId;
        int flag = 0;
        if (e.CommandName == "Edit")
        {
            int fg = 0;
            if (grdvUser.Rows.Count > 0)
                fg = 1;
            returnURL = "User.aspx?MenuId=" + MenuId + "&SearchWord=" + txtkeyword.Text.Trim() + "&SearchFlag=" + fg;
            Response.Redirect("UserDetail.aspx?id=" + int.Parse(e.CommandArgument.ToString())+"&returnURL="+Server.UrlEncode(returnURL));
        }
        else if (e.CommandName == "Delete")
        {
            GridViewRow drv = ((GridViewRow)(((LinkButton)(e.CommandSource)).Parent.Parent)); //此得出的值是表示那行被选中的索引值 
            name = ((Label)drv.FindControl("lblname")).Text.Trim();
            groupName = ((Label)drv.FindControl("lblgroupname")).Text.Trim();
            code = ((Label)drv.FindControl("lblcode")).Text.Trim();
            pwd = ((HiddenField)drv.FindControl("hdfpwd")).Value.Trim();
            isvalid = ((HiddenField)drv.FindControl("hdfIsValid")).Value.Trim();
            groupid = ((HiddenField)drv.FindControl("hdfgroupid")).Value.Trim();
            userId = int.Parse(e.CommandArgument.ToString());
            UserType ut = new UserType();//用户自定义类型
            DataTable UserPermision = ut.GetUserPermisionTableType();
            flag = jtDataAccess.OpUser(JTDataAccess.OpType.Delete, userId, code, name, pwd, int.Parse(isvalid), int.Parse(groupid), UserPermision);

            switch (flag)
            {

                case -1:
                ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert("该用户已经在使用，不允许删除！"), false);
                    break;
                case 0:
                ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert("删除失败！"), false);
                    break;
                default:
                    ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert("删除成功！"), false);
                    break;
            }

        }
       
    }
    protected void grdvUser_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        //首先判断是否是数据行
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //当鼠标停留时更改背景色
            e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#FCFDEE'");
            //当鼠标移开时还原背景色
            e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
            Label lblgroupname = (Label)e.Row.FindControl("lblgroupname");
            Label lblname = (Label)e.Row.FindControl("lblname");
            LinkButton lbtDelete = (LinkButton)e.Row.FindControl("lbtDelete");
            if (lblgroupname != null && lblname != null && lblname.Text == "Admin" && lblgroupname.Text == "Administrators")
            {
                lbtDelete.Visible = false;
            }
            e.Row.Cells[1].Attributes.Add("class", "text");
            
        }
    }
    protected void ibtnsearch_Click(object sender, ImageClickEventArgs e)
    {
        BindUser();
    }
    protected void grdvUser_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        grdvUser.EditIndex = -1;
        BindUser();
    }
    protected void adduser_Click(object sender, EventArgs e)
    {
        int flag = 0;
        if (grdvUser.Rows.Count > 0)
            flag = 1;
        returnURL = "User.aspx?MenuId=" + MenuId + "&SearchWord=" + txtkeyword.Text.Trim() + "&SearchFlag=" + flag;
        Response.Redirect("UserDetail.aspx?returnURL=" + Server.UrlEncode(returnURL));
     
        
    }

    protected void grdvUser_Sorting(object sender, GridViewSortEventArgs e)
    {
        // 从事件参数获取排序数据列
        string sortExpression = e.SortExpression.ToString();

        // 假定为排序方向为“顺序”
        string sortDirection = "ASC";

        // “ASC”与事件参数获取到的排序方向进行比较，进行GridView排序方向参数的修改
        if (sortExpression == this.grdvUser.Attributes["SortExpression"])
        {
            //获得下一次的排序状态
            sortDirection = (this.grdvUser.Attributes["SortDirection"].ToString() == sortDirection ? "DESC" : "ASC");
        }

        // 重新设定GridView排序数据列及排序方向
        this.grdvUser.Attributes["SortExpression"] = sortExpression;
        this.grdvUser.Attributes["SortDirection"] = sortDirection;

        BindUser();
    }
   
    protected void btnexport_Click(object sender, EventArgs e)
    {
      //  DataTable dt = GetExportData();
       // ExcelExport(GetStringWriter(dt), "用户.xls");
        DataTable dt = GetExportData();
        if (grdvUser.Rows.Count == 1 && grdvUser.Rows[0].Cells[0].Text == GridviewControl.EmptyText)
            ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert("没有数据，不需要导出吧！"), false);
        else
        {
            string style = @"<style> .text { mso-number-format:\@;color:#000000 } </style> ";

            HttpContext.Current.Response.ClearContent();
            HttpContext.Current.Response.Charset = "GB2312";
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("用户.xls", System.Text.Encoding.GetEncoding("utf-8")));
            HttpContext.Current.Response.ContentType = "application/ms-excel";

            StringWriter sw = new StringWriter();

            HtmlTextWriter htw = new HtmlTextWriter(sw);
            grdvUser.Columns[4].Visible = false;
            grdvUser.AllowPaging = false;
            grdvUser.AllowSorting = false;
            grdvUser.DataSource = dt;
            grdvUser.DataBind();
            grdvUser.RenderControl(htw);

            // Style is added dynamically
            Response.Write(style);

            Response.Write(sw.ToString());

            Response.End();
        }
        GridviewControl.ResetGridView(this.grdvUser);

    }
    public override void VerifyRenderingInServerForm(Control control)
    {

    }
    protected DataTable GetExportData()
    {
        DataTable dt = new DataTable();
        // 获取GridView排序数据列及排序方向
        string sortExpression = this.grdvUser.Attributes["SortExpression"];
        string sortDirection = this.grdvUser.Attributes["SortDirection"];

        string keyword = txtkeyword.Text.Trim();
        if (CoreTools.ProcessSqlStr(keyword, 0))
        {
            DataSet ds = jtDataAccess.SearchUser(keyword, pager1.PageSize, 0, sortExpression, sortDirection);
            if (CoreTools.CheckDataSet(ds))
            {
                // 根据GridView排序数据列及排序方向设置显示的默认数据视图
                if ((!string.IsNullOrEmpty(sortExpression)) && (!string.IsNullOrEmpty(sortDirection)))
                {
                    ds.Tables[0].DefaultView.Sort = string.Format("{0} {1}", sortExpression, sortDirection);
                }
                dt = ds.Tables[0];

            }
        }
        return dt;

    }
    protected void ExcelExport(StringWriter sw, string exportFileName)
    {

        HttpContext.Current.Response.ClearContent();
        HttpContext.Current.Response.Charset = "GB2312";
        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
        HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(exportFileName, System.Text.Encoding.GetEncoding("utf-8")));
        HttpContext.Current.Response.ContentType = "application/ms-excel";
        // HttpContext.Current.Response.Write("<meta http-equiv=Content-Type content=\"text/html; charset=GB2312\" />");
        HttpContext.Current.Response.Write(sw.ToString());
        HttpContext.Current.Response.End();


    }
    //将datatable中的数据进行组装，比如添加列头（这样excel文件中第一行就看到列头名称） 
    public static StringWriter GetStringWriter(DataTable dt)
    {
        StringWriter sw = new StringWriter();

        //先写列的表头，这样保证如果没有数据也能输出列表头 
        sw.Write("用户组" + "\t ");
        sw.Write("用户编号" + "\t ");
        sw.Write("用户帐号" + "\t ");
        sw.Write("状态" + "\t ");
        sw.Write(sw.NewLine);

        //如果包含数据 
        if (dt != null)
        {
            //写数据 
            foreach (DataRow dr in dt.Rows)
            {
                sw.Write(dr["GroupName"].ToString() + "\t ");
                sw.Write(dr["Code"].ToString() + "\t ");
                sw.Write(dr["Name"].ToString() + "\t ");
                sw.Write(dr["IsValidDesc"].ToString() + "\t ");
                //换行 
                sw.Write(sw.NewLine);
            }
        }
        sw.Close();
        return sw;
    } 

}